package com.platform;

import android.os.Handler;

import com.google.gson.Gson;
import com.platform.contact.ServerConfig;
import com.platform.contact.UserInfo;
import com.platform.net.NetPlatform;
import com.platform.parser.BaseParser;
import com.platform.request.BaseRequest;
import com.platform.request.FrameTransferRequest;
import com.platform.request.HeartBeatRequest;
import com.platform.response.BaseResponse;

import java.net.DatagramPacket;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2019/1/26.
 */

public class GosSession implements NetPlatform.OnRecvCallback{

    private static GosSession session;
    private NetPlatform netPlatform;
    private List<OnResponseCallback> onResponseCallbackList =  new ArrayList<>();
    private BaseParser baseParser;


    public interface OnResponseCallback{
        void responseCallback(BaseResponse response);
    }
    private GosSession(){
        netPlatform = new NetPlatform(this);
        baseParser = new BaseParser();
    }

    public static synchronized GosSession getInstance(){
        if(session==null){
            session = new GosSession();
        }
        return session;
    }

    public void addRecvCallback(OnResponseCallback onResponseCallback){
        if(!onResponseCallbackList.contains(onResponseCallback)){
            onResponseCallbackList.add(onResponseCallback);
        }
    }

    public void removeRecvCallback(OnResponseCallback onResponseCallback){
        if(onResponseCallbackList.contains(onResponseCallback)){
            onResponseCallbackList.remove(onResponseCallback);
        }
    }


    @Override
    public void onCallback(String json) {
        BaseResponse response = baseParser.parse(json);
        for(OnResponseCallback onResponseCallback:onResponseCallbackList){
            onResponseCallback.responseCallback(response);
        }
    }


    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            HeartBeatRequest request = new HeartBeatRequest(UserInfo.id);
            netPlatform.send(request.toJson());
            handler.postDelayed(this,60000);
        }
    };


    public void startHeartBeat(){
        handler.removeCallbacks(runnable);
        handler.post(runnable);
    }

    public void stopHeartBeat(){
        handler.removeCallbacks(runnable);
    }

    public void transferFrame(byte frameData[]){
        FrameTransferRequest request = new FrameTransferRequest(UserInfo.id,UserInfo.toId,frameData);
        netPlatform.send(request.toJson());
    }

}
